package com.jayanslow.lighting.protocol.misc;


import java.math.BigInteger;


public class Bytes {
	public static final int MAX_TEXT_LENGTH = 21;
	
	public static short[] toBytes(long l) {
		BigInteger big = BigInteger.valueOf(l);
		return toBytes(big);
	}
	public static short[] toBytes(BigInteger big) {
		if (big.signum() == -1) return new short[0];
		int length = (int)Math.ceil((double)big.bitLength() / 8);
		short[] ss = new short[length];
		
		for (int i = 0; i < length; i++) {
			BigInteger basePower = BigInteger.valueOf(256).pow(length - i - 1);
			BigInteger[] divMod = big.divideAndRemainder(basePower);
			big = divMod[1];
			ss[i] = divMod[0].shortValue();
		}
		
		return ss;
	}
	public static short[] toBytes(BigInteger big, int max) {
		short[] ss = toBytes(big), r = new short[max];
		int diff = max - ss.length;
		if (diff < 0) diff = 0;
		for (int i = 0; i < max - diff; i++) {
			r[i + diff] = ss[i];
		}
		return r;
	}
	
	public static BigInteger toBigInteger(short[] ss) {
		BigInteger big = BigInteger.ZERO;
		for (int i = 0; i < ss.length; i++) {
			big = big.multiply(BigInteger.valueOf(256));
			big = big.add(BigInteger.valueOf(ss[i]));
		}
		return big;
	}
	
	public static short to16bit(short s1, short s2) {
		short s = (short) (s1 << 8);
		s += s2;
		return s;
	}
	public static int to24bit(short i1, short i2, short i3) {
		int i = i1 << 16;
		i += i2 << 8;
		i += i3;
		return i;
	}
	public static long to32bit(short i1, short i2, short i3, short i4) {
		int i = i1 << 24;
		i += i2 << 16;
		i += i3 << 8;
		i += i4;
		return i;		
	}
}
